package com.atguigu.gmall.common.exception;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice       // 告知框架当前这个类就是一个控制器增强类(全局异常处理类)
public class GlobalExceptionHandler {

    @ExceptionHandler(value = GmallException.class)       // 声明当前的方法就是一个异常处理器
    public Result gmallExceptionHandler(GmallException e) {
        e.printStackTrace();
        ResultCodeEnum resultCodeEnum = e.getResultCodeEnum();
        return Result.build(null , resultCodeEnum) ;
    }

    @ExceptionHandler(value = Exception.class)
    public Result systemExceptionHandler(Exception e) {
        e.printStackTrace();
        return Result.build(null , ResultCodeEnum.SYSTEM_ERROR) ;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();      // FieldError封装的就是校验不同的字段名称和错误提示信息
        // StringBuilder sb = new StringBuilder() ;
        Map<String , String> map = new HashMap<>() ;
        for(FieldError fieldError : fieldErrors) {
            String fieldName = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();     // 获取错误提示信息
            if(!map.containsKey(fieldName)) {
                map.put(fieldName , defaultMessage) ;
            }else {
                String msg = map.get(fieldName);
                msg = msg + ", " + defaultMessage ;
                map.put(fieldName, msg) ;
            }
        }
        String errorMessages = JSON.toJSONString(map) ;
        Result<String> result = new Result<>() ;
        result.setCode(227);
        result.setMessage(errorMessages);
        return result ;
    }

}
